package redis

import (
	"context"
	"fmt"
	"strings"
	"time"

	"github.com/cloudwego/hertz/pkg/common/hlog"
	"github.com/go-redis/redis/v8"
)

const poolSize = 100
const defDBName = 0

var RedisDB *redis.Client

func Init(ip string, port int, user string, password string) error {
	RedisDB = redis.NewClient(&redis.Options{
		Addr:         fmt.Sprintf("%s:%d", ip, port),
		Username:     user,
		Password:     password,
		DB:           defDBName,
		DialTimeout:  10 * time.Second,
		ReadTimeout:  30 * time.Second,
		WriteTimeout: 30 * time.Second,
		PoolSize:     poolSize,
		PoolTimeout:  30 * time.Second,

		OnConnect: func(ctx context.Context, cn *redis.Conn) error {
			return cn.Ping(ctx).Err()
		},
	})
	return GetVersion()
}

// 检测连接是否成功
func GetVersion() error {
	info, err := RedisDB.Info(context.Background(), "server").Result()
	if err != nil {
		return fmt.Errorf("获取redis数据库版本失败,%v", err)
	}

	// 解析返回的info字符串以找到版本号
	for _, line := range strings.Split(info, "\r\n") {
		if strings.HasPrefix(line, "redis_version:") {
			hlog.Infof("redis version:%v", line[13:])
			return nil
		}
	}
	hlog.Warnf("redis version查找失败,%v", info)
	return nil
}
